/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from 'react';
import { Button, List, Row, Col, Avatar, Popconfirm, Empty, Spin } from 'antd';
import { connect } from 'dva';
import KbIcon from '@/components/KbIcon';
import brands from '@kb/brands';
import { firstUpperCase } from '@/utils/utils';
import classNames from 'classnames';
import { Agree, Branch, Courier, Kop, Third } from './add';
import { names } from './config';
import styles from './index.less';

const { Item: ListItem } = List;
// 获取单号源的方法key表
const sourceKeys = [
  // 'agree', 
  // 'branch', 
  // 'courier', 
  'kop', 
  'third', 
  // 'group'
];
const deleteKeys = ['courier', 'kop'];
// 非第三方内容展示对应的key值
const infoKeysConfig = {
  courier: ['branchName', 'courierName', 'courierPhone'],
  kop: ['account'],
  branch: ['branchName'],
  agree: ['realName', 'courierMobile'],
};

// 创建loading状态
const createLoading = loading => {
  const loadingGroup = {};
  sourceKeys.map(key => {
    loadingGroup[`getting_${key}`] = loading.effects[`source/get${firstUpperCase(key)}`];
  });
  return loadingGroup;
};
// 余量显示
const renderRest = (key, data, disabled) => {
  const quantity = data.quantity || ( data.quantity == 0 && data.quantity.toString() )
  const waybill_sum = data.waybill_sum && data.waybill_sum.toString()
  const d_num = data.num && data.num.toString()

  const num = quantity || waybill_sum || d_num
  let text = '';
  let cls = 'gray';
  if (num == '-9999') {
    text = '不限';
    cls = 'green';
  } else if (num || num == 0) {
    cls = 'red';
    text = `剩余 ${num} 个`;
  } else {
    text = '';
  }
  return key === 'branch' ? (
    !disabled ? (
      <span className={styles.red}>{data.price} 元/票</span>
    ) : null
  ) : key === "agree" ? (
    <>
      {Number(data.waybill_price) ? <span className={styles.red}>{data.waybill_price} 元/单&nbsp;&nbsp;</span> : ' '}
      {text ? <span className={styles[cls]}>{text}</span> : ' '}
    </>
  ) : text ? (
    <span className={styles[cls]}>{text}</span>
  ) : (
    <></>
  );
};

// 品牌名称
const brandData = {};
brands.map(item => {
  brandData[item.code] = item;
});
const renderBrandName = key => {
  const { name = '' } = brandData[key] || {};
  return name;
};

// 添加组件合并组
const AddGroups = props => {
  const { children, type } = props;
  switch (type) {
    case 'agree':
      return <Agree>{children}</Agree>;
    case 'branch':
      return <Branch>{children}</Branch>;
    case 'courier':
      return <Courier>{children}</Courier>;
    case 'kop':
      return <Kop>{children}</Kop>;
    case 'third':
      return <Third>{children}</Third>;
    default:
      break;
  }
  return null;
};

// 单号源行内列内容渲染组件
const SourceCol = props => {
  const {
    disabled,
    iitem,
    item,
    name,
    span: [span1, span2, span3],
  } = props;
  const { infoKeys } = item;
  return infoKeys ? (
    <>
      <Col span={span1}>
        <Row type="flex" align="middle" gutter={16} className={styles.avatar}>
          <Col>
            <Avatar
              size="large"
              src={
                iitem.logo
                  ? iitem.logo.replace('http:', '')
                  : `//img.kuaidihelp.com/brand_logo/icon_${iitem.brand}.png`
              }
            />
          </Col>
          <Col>
            <div>{renderBrandName(iitem.brand) || iitem.brand_name || iitem.brandInfo}</div>
            {name && <div className={styles.avatar_desc}>{name}</div>}
          </Col>
        </Row>
      </Col>
      {item.infoKeys && (
        <Col span={span2} className={styles.info}>
          {item.infoKeys.map(key => (
            <span key={key}>{iitem[key]}</span>
          ))}
        </Col>
      )}
      <Col span={span3}>{renderRest(item.key, iitem, disabled)}</Col>
    </>
  ) : (
    <Row>
      <Col span={span1}>
        <Row type="flex" align="middle" gutter={16} className={styles.avatar}>
          <Col>
            <Avatar
              size="large"
              src={`//img.kuaidihelp.com/brand_logo/icon_${iitem.kb_code}.png`}
            />
          </Col>
          <Col>
            <div>{renderBrandName(iitem.kb_code) || iitem.brand_name}</div>
            {name && <div className={styles.avatar_desc}>{name}</div>}
          </Col>
        </Row>
      </Col>
      <Col span={span2} className={styles.info}>
        {iitem.branch_name}
      </Col>
      <Col span={span3} className={styles.red}>
        {renderRest(item.key, iitem, disabled)}
      </Col>
    </Row>
  );
};

@connect(({ loading, source }) => ({
  source,
  authing: loading.effects['source/auth'],
  canceling: loading.effects['source/cancel'],
  getAllSource: loading.effects['source/getAllSource'],
  loadingGroup: createLoading(loading),
}))
class KbSource extends Component {
  static defaultProps = {
    onSelect: () => {},
    selectOnly: false,
  };

  constructor(props) {
    super(props);
    this.state = {};

    this.columns = [
      // {
      //   key: 'courier',
      //   infoKeys: infoKeysConfig.courier,
      //   rowKey: 'authId',
      // },
      {
        key: 'kop',
        infoKeys: infoKeysConfig.kop,
        rowKey: 'auth_id',
      },
      // {
      //   key: 'branch',
      //   infoKeys: infoKeysConfig.branch,
      //   rowKey: 'branchCode',
      // },
      // {
      //   key: 'agree',
      //   infoKeys: infoKeysConfig.agree,
      // },
      // {
      //   key: 'group',
      // },
    ];
  }

  componentDidMount() {
    this.getSource();
  }

  // 获取单号源列表
  getSource(key) {
    const { dispatch } = this.props;
    dispatch({
      type: 'source/getAllSource',
    })
  }

  // 移除
  onCancel = (kind, item, activeId) => {
    const { dispatch } = this.props;
    let payload;
    let sourceKey = kind;
    const { auth_id, relation_id } = item;
    switch (kind) {
      case 'courier':
        const { authId } = item;
        payload = { auth_id: authId };
        break;
      case 'kop':
        const { accountId: account_id } = item;
        payload = { auth_id };
        break;
      case 'taobao':
        payload = { auth_id };
        sourceKey = 'third';
        break;
      case 'wuliuyun':
        payload = { auth_id };
        sourceKey = 'third';
        break;
      case 'pindd':
        payload = { auth_id };
        sourceKey = 'third';
        break;
      case 'pdd_universal':
        payload = { auth_id };
        sourceKey = 'third';
        break;
      default:
        break;
    }
    this.activeId = activeId;
    return dispatch({
      type: 'source/cancel',
      kind,
      payload,
    }).then(res => {
      const { code } = res;
      if (code == 0 && !activeId.includes('rest')) {
        this.getSource(sourceKey);
        // 单号源设置页面，获取最新的下拉框数据
        dispatch({
          type:"setter/getOperatorOrderSourceList",
        })
        dispatch({
          type: 'setter/getSetterList',
          payload: {
            page: 1,
            site_id: 'all',
            keyword: '',
          },
        })
      }
      return res;
    });
  };

  // 点击选择
  onSelect = this.props.onSelect;

  render() {
    const { source, loadingGroup, style, authing, className, selectOnly, canceling } = this.props;
    const span = selectOnly ? [8, 12, 4] : [4, 8, 4];
    const isDataReady = Object.keys(source.allSource).length > 0    // 判断数据有没有加载完
    const isThirdReady = !!(source.allSource.third && source.allSource.third.length > 0)  // 判断第三方数据有没有加载完
    const sourceArr = []
    for (const key in source.allSource) {
      sourceArr.push( source.allSource[key].length ) 
    }
    const isSourceEmpty = sourceArr.reduce((p,c)=>p+c,0) > 0    // 判断单号源数据是否为空

    return (
      <div className={classNames('kb-list', className)} style={style}>
        {this.columns.map(item => {
          const title = names[item.key].label;
          const has = !!( isDataReady && source.allSource[item.key].length);
          return !has ? null : (
            <List
              key={item.key}
              header={
                selectOnly || item.key === 'group' ? (
                  title
                ) : (
                  <Row>
                    <Col span={12}>{title}</Col>
                    <Col span={12} style={{ textAlign: 'right' }}>
                      <AddGroups type={item.key}>
                        <a className={styles.bar}>
                          <KbIcon type="plus-circle" />
                          <span>添加</span>
                        </a>
                      </AddGroups>
                    </Col>
                  </Row>
                )
              }
              loading={loadingGroup[item.key]}
            >
              {has ? (
                source.allSource[item.key].map((iitem, iindex) => {
                  const disabled = item.key === 'branch' && iitem.status !== '使用中';
                  const activeId = `${item.key}_${iindex}`;
                  return selectOnly && disabled ? null : (
                    <ListItem
                      onClick={this.onSelect.bind(this, item.key, iitem)}
                      key={iitem[item.rowKey || 'id']}
                      className={disabled ? 'kb-list_disabled' : ''}
                    >
                      <Row>
                        {iitem.waybill_share_info ? ( // 团队分享单号源
                          <SourceCol
                            disabled={disabled}
                            item={{
                              ...item,
                              infoKeys: infoKeysConfig[iitem.waybill_share_info.type],
                            }}
                            iitem={iitem.waybill_share_info.source}
                            span={span}
                            name={iitem.group_name}
                          />
                        ) : (
                          <SourceCol disabled={disabled} item={item} iitem={iitem} span={span} />
                        )}
                        {!selectOnly && item.type !== 'group' && (
                          <>
                            {item.key === 'branch' && (
                              <Col span={4} className={!disabled ? styles.green : ''}>
                                {iitem.status}
                              </Col>
                            )}
                            {deleteKeys.includes(item.key) && (
                              <Col span={4}>
                                <Popconfirm
                                  placement="topRight"
                                  title="确定删除吗？"
                                  onConfirm={this.onCancel.bind(this, item.key, iitem, activeId)}
                                >
                                  <Button
                                    loading={canceling && this.activeId === activeId}
                                    type="link"
                                  >
                                    删除
                                  </Button>
                                </Popconfirm>
                              </Col>
                            )}
                          </>
                        )}
                      </Row>
                    </ListItem>
                  );
                })
              ) : (
                <div>
                  <Empty
                    description={item.noDataText || '暂无数据'}
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                  />
                </div>
              )}
            </List>
          );
        })}

        {/* 第三方 */}
        <Spin spinning={!!authing}>
          { isThirdReady && source.allSource.third.map(item => {
            const { list } = item;
            const hasList = list && list.length > 0;
            return hasList
              ? list.map((iitem, iindex) => {
                  const { source: iitemSource, ...iitemRest } = iitem;
                  const has = iitem.status == 1 && iitemSource && iitemSource.length;
                  const activeId = `${item.key}_${iindex}`;
                  const title = (
                    <>
                      {names[item.key].label}
                      {iitem.user_name && <>（{iitem.user_name}）</>}
                    </>
                  );
                  return selectOnly && !has ? null : (
                    <List
                      key={iitem.owner_id || iitem.auth_id || 'nodata'}
                      header={
                        selectOnly ? (
                          title
                        ) : (
                          <Row>
                            <Col span={12}>{title}</Col>
                            {(iitem.status == 1 || iitem.status == 2) && (
                              <Col span={12} style={{ textAlign: 'right' }}>
                                <Popconfirm
                                  placement="topRight"
                                  title={
                                    item.key.includes('pindd') ? (
                                      <>
                                        取消拼多多单号源授权，将停止导入该店铺的订单，
                                        <br />
                                        并退出该店铺的拼多多专版。
                                        <br />
                                        您确认要取消吗？
                                      </>
                                    ) : (
                                      '您确定要取消授权吗？'
                                    )
                                  }
                                  onConfirm={this.onCancel.bind(this, item.key, iitem, activeId)}
                                >
                                  <a className={styles.bar}>
                                    <KbIcon
                                      type={
                                        canceling && this.activeId === activeId
                                          ? 'loading'
                                          : 'close-circle'
                                      }
                                    />
                                    <span>取消授权</span>
                                  </a>
                                </Popconfirm>
                              </Col>
                            )}
                          </Row>
                        )
                      }
                      loading={loadingGroup.third}
                    >
                      {has ? (
                        iitemSource.map(iiitem => (
                          <ListItem
                            key={iiitem.branch_code}
                            onClick={this.onSelect.bind(this, item.key, {
                              ...iiitem,
                              account: iitemRest,
                            })}
                          >
                            <SourceCol item={item} iitem={iiitem} span={span} />
                          </ListItem>
                        ))
                      ) : (
                        <div>
                          <Empty
                            description={
                              iitem.status == 0 ? (
                                <span>
                                  你还未授权，请
                                  {item.key === 'wuliuyun' ? (
                                    <>
                                      <Third type={item.key} by="account">
                                        <a>账号授权</a>
                                      </Third>
                                      或
                                      <Third type={item.key} by="token">
                                        <a>令牌授权</a>
                                      </Third>
                                    </>
                                  ) : (
                                    <Third type={item.key}>
                                      <a>立即授权</a>
                                    </Third>
                                  )}
                                  使用
                                </span>
                              ) : iitem.status == 2 ? (
                                <span>
                                  该账号授权已失效，请
                                  <Third
                                    disabled={canceling}
                                    type={item.key}
                                    onCancel={this.onCancel.bind(
                                      this,
                                      item.key,
                                      iitem,
                                      `${activeId}_rest`
                                    )}
                                  >
                                    <a>
                                      {canceling && <KbIcon type="loading" />}
                                      重新授权
                                    </a>
                                  </Third>
                                </span>
                              ) : (
                                <span>
                                  你还没有可使用的电子面单，请在
                                  <a target="_blank" href={names[item.key].path}>
                                    {names[item.key].pathname}
                                  </a>
                                  申请使用
                                </span>
                              )
                            }
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                          />
                        </div>
                      )}
                    </List>
                  );
                })
              : null;
          })}
        </Spin>

        {/* 数据为空的显示 */}
        {
          !isSourceEmpty && (
          <Empty
            description="暂无数据"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
)
        }
      </div>
    );
  }
}

KbSource.names = names;

export default KbSource;
